package com.zsinfo.guoss.supplier.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.example.netcenter.Event.Response;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.ErrorBean;
import com.google.gson.Gson;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.base.BaseActivity;
import com.zsinfo.guoss.supplier.customize.AlertDialog;
import com.zsinfo.guoss.supplier.customize.Keyboard;
import com.zsinfo.guoss.supplier.customize.PayEditText;
import com.zsinfo.guoss.supplier.utils.Md5util;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;

/**
 * Created by lixl on 2018/12/5.
 * <p>
 * desc:退款界面
 *
 * 1.判断当前是否有银行卡,
 * 如果有,显示第一张;
 * 如果没有,则不显示
 *
 * 2.判断是否设置了支付密码
 * 有,直接调起输入密码;
 * 没有,则提示前往设置支付密码
 */
public class RefundActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_account;
    private ImageView iv_account_type;  //银行卡类型
    private TextView tv_account_card;  //卡号
    private EditText et_input_money;
    private TextView tv_user_money;
    private TextView tv_all_money;  //全部退款
    private Button btn_start_refund;

    private View mPopView;
    private PopupWindow mPopupWindow;
    private TextView pop_forget_pwd;  //pop 忘记密码
    private ImageView pop_back;  //pop 返回键
    private PayEditText payEditText;  //pop 密码输入框
    private Keyboard keyboard;  //pop 自定义数字键盘

    private String money;  //用户输入的金额
    private int canUseMoney;  //可用金额
    private int type = 1; //退款类型，1国产，2进口
    private String payPwd = "";  //支付密码
    private String bankCardId;  //银行卡id：注意 支付宝没有id
    private String bankCardName;  //银行卡发行商名
    private String bankCardNo;  //银行卡号
    private AlertDialog myDialog;
    //数字键盘
    private static final String[] KEY = new String[]{
            "1", "2", "3",
            "4", "5", "6",
            "7", "8", "9",
            "<<", "0", "完成"
    };

    @Override
    protected int getContentLayoutRes() {
        return R.layout.activity_refund;
    }

    @Override
    protected void initView() {
        setTitle("退款");
        setBackAndLeftTitle("").setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        type = getIntent().getExtras().getInt("type");
        payPwd = getIntent().getExtras().getString("payPwd");
        canUseMoney = getIntent().getExtras().getInt("canUseMoney");

        myDialog = new AlertDialog(this).builder();

        ll_account = findViewById(R.id.ll_account);
        iv_account_type = findViewById(R.id.iv_account_type);
        tv_account_card = findViewById(R.id.tv_account_card);
        et_input_money = findViewById(R.id.et_input_money);
        tv_user_money = findViewById(R.id.tv_user_money);
        tv_all_money = findViewById(R.id.tv_all_money);
        btn_start_refund = findViewById(R.id.btn_start_refund);

        ll_account.setOnClickListener(this);
        tv_all_money.setOnClickListener(this);
        btn_start_refund.setOnClickListener(this);

        initPopWindow();

        tv_user_money.setText(canUseMoney+"元");

        et_input_money.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //判断当前输入的金额，还需要减法
                Log.e("lixl", "金额------"+s.toString());
                //java.lang.NumberFormatException: For input string: ""
                if (s.toString().length() >= 1) {
                    int inputNum = Integer.parseInt(s.toString());
                    if (inputNum == 0) {
                        et_input_money.setText("");
                        showToast("缴纳金额最低1元起");
                    } else if (inputNum > canUseMoney) {
                        showToast("余额不足");
                    } else {
                        int deleteNum = canUseMoney - inputNum;  //剩余的钱
                        tv_user_money.setText(deleteNum + "元");
                    }
                } else {
                    tv_user_money.setText(canUseMoney+"元");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initNetData() {

    }

    @Override
    protected void customDestroy() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_account:
                //跳转银行卡列表
                startActivityForResult(new Intent(RefundActivity.this, RefundAccountListActivity.class), 3);
                break;
            case R.id.tv_all_money:
                //全部退款
                et_input_money.setText(canUseMoney+"");
                et_input_money.setSelection(et_input_money.getText().toString().trim().length());
                tv_user_money.setText("0元");
                break;
            case R.id.btn_start_refund:
                //先判断是否有支付密码
                if (TextUtils.isEmpty(payPwd)){
                    refundDialog();
                    return;
                }
                //再判断是否有选择退款账户
                if (TextUtils.isEmpty(bankCardName) && TextUtils.isEmpty(bankCardNo)){
                    showToast("请先选择退款账户");
                    return;
                }
                //再判断是否输入金额
                money = et_input_money.getText().toString().trim();
                if (TextUtils.isEmpty(money)){
                    showToast("请输入金额");
                    return;
                } else if (Integer.parseInt(money) == 0){
                    showToast("缴纳金额最低1元起");
                    return;
                } else if (Integer.parseInt(money) > canUseMoney){
                    showToast("当前可退款余额不足，请重新输入");
                    return;
                }

                showPopWindow();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3 && resultCode == 4) {
            bankCardId = data.getStringExtra("bankCardId");
            bankCardName = data.getStringExtra("bankCardName");
            bankCardNo = data.getStringExtra("bankCardNo");
            tv_account_card.setText(bankCardName + "(" + bankCardNo + ")");
            Log.e("lixl", bankCardId);
            Log.e("lixl", bankCardName);
            Log.e("lixl", bankCardNo);
        }
    }

    /**
     * 国产退款
     * @param money
     */
    private void setChainRefund(String bankCardId, String pwd, String money){
        GetNetCenter().GetNetCenter(this,
                RetrofitBuilder.CreateApi().CHAIN_REFUND(
                        ConstantsCode.domestic_deposit_refund,
                        SharedPreferencesUtil.getID(),
                        bankCardId, Md5util.GetMD5Code(pwd), money), new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());
                        startActivity(new Intent(RefundActivity.this, RefundResultActivity.class));
                        finish();
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (e.getMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            showToast(errorBean.getMsg());

                        } else {
                            showToast(e.getMessage());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }

    /**
     * 进口退款
     * @param money
     */
    private void setImportRefund(String bankCardId, String pwd, String money){
        GetNetCenter().GetNetCenter(this,
                RetrofitBuilder.CreateApi().IMPORT_REFUND(
                        ConstantsCode.import_deposit_refund,
                        SharedPreferencesUtil.getID(),
                        bankCardId, Md5util.GetMD5Code(pwd), money), new Response() {
                    @Override
                    public void OK(Object data) {
                        Log.e("lixl", data.toString());
                        startActivity(new Intent(RefundActivity.this, RefundResultActivity.class));
                        finish();
                    }

                    @Override
                    public void Fail(Throwable e) {
                        Log.e("lixl", e.getMessage());
                        if (e.getMessage().contains("Code")) {
                            ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);
                            showToast(errorBean.getMsg());

                        } else {
                            showToast(e.getMessage());
                        }
                    }

                    @Override
                    public void complete() {

                    }
                });
    }

    /**
     * 支付密码 提示框
     */
    private void refundDialog(){
        myDialog.setGone()
                .setMsg("还未设置支付密码")
                .setNegativeButton("去设置", R.color.n_blue, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(RefundActivity.this, PaySettingsActivity.class));
                    }
                })
                .setPositiveButton("取消", R.color.black, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                })
                .show();
    }

    /**
     * 支付密码弹出框
     */
    private void initPopWindow() {
        // 将布局文件转换成View对象，popupview 内容视图
        mPopView = getLayoutInflater().inflate(R.layout.view_pay_pop_menu, null);
        pop_forget_pwd = (TextView) mPopView.findViewById(R.id.pop_forget_pwd);
        pop_back = (ImageView) mPopView.findViewById(R.id.pop_back);
        keyboard = (Keyboard) mPopView.findViewById(R.id.key_pay);
        payEditText = (PayEditText) mPopView.findViewById(R.id.PayEditText_pay);
        keyboard.setOnClickKeyboardListener(new Keyboard.OnClickKeyboardListener() {
            @Override
            public void onKeyClick(int position, String value) {
                if (position < 11 && position != 9) {
                    payEditText.add(value);
                } else if (position == 9) {
                    payEditText.remove();
                } else if (position == 11) {
                    //当点击d键盘上的完成时候，也可以通过payEditText.getText()获取密码，此时不应该注册OnInputFinishedListener接口
                    String password = payEditText.getText();
                    if (TextUtils.isEmpty(password)) {
                        showToast("请输入密码");
                        return;
                    }
                    if (password.length() < 6) {
                        showToast("密码不能少于6位");
                        return;
                    }
                }
                keyboardFinish(payEditText.getText().toString());
            }
        });
        // 将转换的View放置到 新建一个popuwindow对象中
        mPopupWindow = new PopupWindow(mPopView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                dip2px(400)
        );
        // 点击popuwindow外让其消失
        mPopupWindow.setOutsideTouchable(true);

        pop_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopupWindow != null)
                    mPopupWindow.dismiss();
            }
        });
        pop_forget_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //注意：点击忘记密码，需要进入手机短信验证Fragment
                Intent intent = new Intent(RefundActivity.this, PaySettingsActivity.class);
                intent.putExtra("fragment_switch", "Fragment_Validate");
                startActivity(intent);
            }
        });

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = RefundActivity.this.getWindow().getAttributes();
                lp.alpha = 1f; //0.0-1.0
                RefundActivity.this.getWindow().setAttributes(lp);
                clearPassword();
            }
        });
    }

    /**
     * 弹出键盘
     */
    public void showPopWindow() {
        try {
            if (mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            } else {
                WindowManager.LayoutParams lp = this.getWindow().getAttributes();
                lp.alpha = 0.5f; //0.0-1.0
                this.getWindow().setAttributes(lp);
                // 设置PopupWindow 显示的形式 底部或者下拉等
                // 在某个位置显示
                mPopupWindow.showAtLocation(btn_start_refund, Gravity.BOTTOM, 0, 0);
                // 作为下拉视图显示
                keyboard.setKeyboardKeys(KEY);
                // mPopupWindow.showAsDropDown(mPopView, Gravity.CENTER, 200, 300);
            }
        } catch (Exception e) {
            Log.e("dd", "ShowPopWindow: ");
        }
    }

    /**
     * 隐藏键盘
     */
    public void hiddenPopWindow(){
        try {
            if (mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
        } catch (Exception e) {
            Log.e("dd", "ShowPopWindow: ");
        }
    }

    /**
     * 清空密码
     */
    private void clearPassword() {
        for (int i = 0; i < 6; i++) {
            payEditText.remove();
        }
    }

    /**
     * 键盘输入后操作
     * @param pwd
     */
    private void keyboardFinish(String pwd) {
        if (pwd.length() == 6) {
            hiddenPopWindow();
            //再判断退给谁
            if (type == 1){
                setChainRefund(bankCardId, pwd, money);
            } else {
                setImportRefund(bankCardId, pwd, money);
            }
        }
    }

    /**
     * 根据手机的分辨率from dp 的单位 转成为 px(像素)
     */
    private int dip2px(float dpValue) {
        final float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}
